<template>
  <div class="avatar-upload">
    <div v-if="modelValue" class="avatar-upload__box">
      <el-avatar shape="square" :size="120" :src="modelValue" />

      <div class="mark">
        <el-button @click="$emit('update:modelValue', '')">x</el-button>
      </div>
    </div>

    <div v-else class="avatar-upload__default">
      <span>选择头像</span>

      <input class="input" type="file" @change="handleFileChange" />
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "AvatarUpload",

  props: {
    modelValue: { type: String, default: "" },
  },

  emits: ["update:modelValue"],

  methods: {
    handleFileChange(event) {
      // 1. 获取当前的 File 对象
      const file = event.target.files[0];

      // 2. 组装 FormData  PS: axios 0.27.0 之后，可以不用组装 FormData
      // const formData = new FormData();
      // formData.append("file", file);
      // formData.append("name", "张三");

      // 3. 调用接口，使用 formData 作为请求体参数，将请求头中的 Content-Type 设置为 "multipart/form-data"
      request
        .post(
          "/app/base/comm/upload",
          {
            file,
            name: "张三",
          },
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        )
        .then((result) => {
          console.log("result", result);

          // 触发自定义事件写入数据
          this.$emit("update:modelValue", result);
        });

      // console.log(target.files);
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-upload {
  width: 120px;
  height: 120px;
  background-color: #eee;
  overflow: hidden;

  &__default {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    color: #606266;
    cursor: pointer;

    &:hover {
      color: red;
    }
  }

  &__box {
    position: relative;

    &:hover {
      .mark {
        display: flex;
      }
    }
  }

  .input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
  }

  .mark {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.5);
  }
}
</style>
